﻿using System.Globalization;
using System.Web;
using Orchard.Environment.Extensions;
using Orchard.Localization.Services;

namespace Vitus.Localization.Selectors
{
    [OrchardFeature("Vitus.DataTokenCultureSelector")]
    public class DataTokenCultureSelector : ICultureSelector
    {
        public const string CULTURE_TOKEN = "culture";

        public CultureSelectorResult GetCulture(HttpContextBase context)
        {
            if (context == null)
            {
                return null;
            }

            object cultureFromUrl;

            if (!context.Request.RequestContext.RouteData.DataTokens.TryGetValue(CULTURE_TOKEN, out cultureFromUrl))
            {
                return null;
            }

            try
            {
                var cultureInfo = CultureInfo.GetCultureInfo(cultureFromUrl.ToString());
                return new CultureSelectorResult { Priority = 10, CultureName = cultureInfo.Name };
            }
            catch
            {
                return null;
            }
        }
    }
}